﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PIMS
{
    static class Program
    {
        private const int SW_HIDE = 0; 　　//从任务栏隐藏
        private const int SW_NORMAL = 1;    //正常弹出窗体 
        private const int SW_MAXIMIZE = 3;    //最大化弹出窗体 
        private const int SW_SHOWNOACTIVATE = 4; 　　//激活窗体/恢复窗体/还原窗体
        private const int SW_SHOW = 5; 　　//显示窗体，最小化时不会最大化
        private const int SW_MINIMIZE = 6; 　　//最小化
        private const int SW_RESTORE = 9;
        private const int SW_SHOWDEFAULT = 10; 

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool createdNew = true;
            using (Mutex mutex = new Mutex(true, "HBSPIMS", out createdNew))
            {
                if (createdNew)
                {

                    //Task.Run(() => {
                    //    CreateWebHostBuilder(new string[] { }).Build().Run();
                    //});


                    // Add the event handler for handling non-UI thread exceptions to the event.      
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new FormContainer());
                }
                else
                {
                    Process current = Process.GetCurrentProcess();
                    //  MessageBox.Show("已运行一个程序了", current.ProcessName);
                    Process[] processes = Process.GetProcessesByName(current.ProcessName);
                    foreach (Process process in processes)
                    {
                        if (process.Id != current.Id)
                        {
                            ShowWindowAsync(process.MainWindowHandle, SW_MAXIMIZE); //显示，可以注释掉       
                            SetForegroundWindow(process.MainWindowHandle);
                            break;
                        }
                    }
                }
            }



        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                .UseUrls("http://0.0.0.0:23198")//, "https://0.0.0.0:23199")
                   .UseStartup<Startup>();
        }

        // Handle the UI exceptions by showing a dialog box, and asking the user whether     
        // or not they wish to abort execution.     
        // NOTE: This exception cannot be kept from terminating the application - it can only      
        // log the event, and inform the user about it.  
        //这个是没法阻止程序退出的,只能做记录
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //e.IsTerminating;//这个属性告诉我们这个异常是否会导致应用终止

            Exception ex = (Exception)e.ExceptionObject;
            string errorMsg = "An application error occurred. Please contact the adminstrator " +
            "with the following information:\n\n";
            errorMsg += ex.Message + "\n\nStack Trace:\n" + ex.StackTrace;

            System.Windows.Forms.MessageBox.Show("异常句柄:" + errorMsg);
        }

        #region
        /// <summary>
        /// 获取正在运行的实例，没有运行的实例返回null;
        /// </summary>
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 显示已运行的程序。
        /// </summary>
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, SW_NORMAL); //显示，可以注释掉
            SetForegroundWindow(instance.MainWindowHandle);            //放到前端
        }
        /// <summary>
        /// 该函数设置由不同线程产生的窗口的显示状态。
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="cmdShow">指定窗口如何显示。查看允许值列表，请查阅ShowWlndow函数的说明部分。</param>
        /// <returns>如果函数原来可见，返回值为非零；如果函数原来被隐藏，返回值为零。</returns>
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        /// <summary>
        /// 该函数将创建指定窗口的线程设置到前台，并且激活该窗口。键盘输入转向该窗口，并为用户改各种可视的记号。系统给创建前台窗口的线程分配的权限稍高于其他线程。
        /// </summary>
        /// <param name="hWnd">将被激活并被调入前台的窗口句柄。</param>
        /// <returns>如果窗口设入了前台，返回值为非零；如果窗口未被设入前台，返回值为零。</returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        #endregion
    }
}
